#include "choosefrienddialog.h"
#include "debug.h"

ChooseFriendItem::ChooseFriendItem(ChooseFriendDialog *owner, const QString &userId, const QIcon &avatar,
                                   const QString &name, bool checked)
    : _userId(userId)
{
    // 1.设置控件的基本属性
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 2. 设置布局管理器
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(20, 0, 20, 0);
    this->setLayout(layout);

    // 3. 创建复选框
    _checkBox = new QCheckBox();
    _checkBox->setChecked(checked);
    _checkBox->setFixedSize(25, 25);
    _checkBox->setFixedSize(25, 25);
    QString style = "QCheckBox { background-color: transparent; } QCheckBox::indicator { width: 20px; height: 20px; "
                    "image: url(:/resource/image/unchecked.png);}";
    style += "QCheckBox::indicator:checked { image: url(:/resource/image/checked.png);}";
    _checkBox->setStyleSheet(style);

    // 4. 创建头像
    _avatarBtn = new QPushButton();
    _avatarBtn->setFixedSize(40, 40);
    _avatarBtn->setIconSize(QSize(40, 40));
    _avatarBtn->setIcon(avatar);

    // 5. 创建昵称
    _nameLabel = new QLabel();
    _nameLabel->setText(name);
    _nameLabel->setStyleSheet("QLabel {background-color: transparent;}");

    // 6. 添加到布局管理器中
    layout->addWidget(_checkBox);
    layout->addWidget(_avatarBtn);
    layout->addWidget(_nameLabel);

    // 7. 连接信号槽
    connect(_checkBox, &QCheckBox::toggled, this,
            [=](bool checked)
            {
                if (checked)
                {
                    owner->addSelectedFriend(userId, avatar, name);
                }
                else
                {
                    owner->deleteSelectedFriend(userId);
                }
            });
}

void ChooseFriendItem::paintEvent(QPaintEvent *event)
{
    (void) event;
    QPainter painter(this);
    if (_isHover)
    {
        painter.fillRect(this->rect(), QColor(230, 230, 230));
    }
    else
    {
        painter.fillRect(this->rect(), QColor(255, 255, 255));
    }
}

void ChooseFriendItem::enterEvent(QEnterEvent *event)
{
    (void) event;
    _isHover = true;
    this->update();
}

void ChooseFriendItem::leaveEvent(QEvent *event)
{
    (void) event;
    _isHover = true;
    this->update();
}

ChooseFriendDialog::ChooseFriendDialog(QWidget *parent, const QString &userId)
{
    // 1. 设置窗口的基本属性
    this->setWindowTitle("选择好友");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setFixedSize(750, 750);
    this->setStyleSheet("QDialog { background-color: rgb(255, 255, 255);}");
    this->setAttribute(Qt::WA_DeleteOnClose);

    // 2. 创建布局管理器
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    this->setLayout(layout);

    // 3. 针对左侧窗口进行初始化
    initLeft(layout);

    // 4. 针对右侧窗口进行初始化
    initRight(layout);
}

void ChooseFriendDialog::addFriend(const QString &userId, const QIcon &avatar, const QString &name, bool checked)
{
    ChooseFriendItem *item = new ChooseFriendItem(this, userId, avatar, name, checked);
    _totalContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::addSelectedFriend(const QString &userId, const QIcon &avatar, const QString &name)
{
    ChooseFriendItem *item = new ChooseFriendItem(this, userId, avatar, name, true);
    _selectedContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::deleteSelectedFriend(const QString &userId)
{
    // 遍历 selectedContainer 中的每个 item ，对比每个 item 里的 userId 是否是需要删除的 userId
    QVBoxLayout *vlayout = dynamic_cast<QVBoxLayout *>(_selectedContainer->layout());
    for (int i = vlayout->count() - 1; i >= 0; i--)
    {
        auto *item = vlayout->itemAt(i);
        if (item == nullptr || item->widget() == nullptr)
        {
            continue;
        }
        ChooseFriendItem *chooseFriendItem = dynamic_cast<ChooseFriendItem *>(item->widget());
        if (chooseFriendItem->getUserId() != userId)
        {
            continue;
        }
        vlayout->removeWidget(chooseFriendItem);

        // 由于要删除的 ChooseFriendItem 内部的 checkBox 还在使用，不能直接删除
        // 使用 delteLater 可以将删除操作在 Qt 判断使用完成后再自动删除
        chooseFriendItem->deleteLater();
    }

    // 遍历左侧列表，取消对应 item 的 checkBox 勾选状态
    QVBoxLayout *vlayoutLeft = dynamic_cast<QVBoxLayout *>(_totalContainer->layout());
    for (int i = 0; i < vlayoutLeft->count(); i++)
    {
        auto *item = vlayoutLeft->itemAt(i);
        if (item == nullptr || item->widget() == nullptr)
        {
            continue;
        }
        ChooseFriendItem *chooseFriendItem = dynamic_cast<ChooseFriendItem *>(item->widget());
        if (chooseFriendItem->getUserId() != userId)
        {
            continue;
        }
        // 取消 checkBox 选中状态
        chooseFriendItem->getCheckBox()->setChecked(false);
    }
}

void ChooseFriendDialog::initLeft(QHBoxLayout *layout)
{
    // 1. 创建滚动区域
    QScrollArea *scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px;}");
    scrollArea->verticalScrollBar()->setStyleSheet(
        "QScrollBar:vertical { width: 2px; background-color: rgb(255, 255, 255) }");
    scrollArea->setStyleSheet("QScrollArea { border:none; }");
    layout->addWidget(scrollArea, 1);

    // 2. 创建 QWidget 设置到滚动区域中
    _totalContainer = new QWidget();
    _totalContainer->setObjectName("_totalContainer");
    _totalContainer->setStyleSheet("#_totalContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(_totalContainer);

    // 3. 创建左侧子窗口内部的垂直布局管理器
    QVBoxLayout *vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    _totalContainer->setLayout(vlayout);

    // 测试效果
#if TEST_UI
    QIcon defaultAvatar(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 30; i++)
    {
        this->addFriend(QString::number(1000 + i), defaultAvatar, "张三" + QString::number(i), false);
    }
#endif
}

void ChooseFriendDialog::initRight(QHBoxLayout *layout)
{
    // 1. 创建右侧的布局管理器
    QGridLayout *gridLayout = new QGridLayout();
    gridLayout->setContentsMargins(20, 0, 20, 20);
    gridLayout->setSpacing(10);
    layout->addLayout(gridLayout, 1);

    // 2. 创建 提示 label
    QLabel *tipLabel = new QLabel();
    tipLabel->setText("选择联系人");
    tipLabel->setFixedHeight(30);
    tipLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    tipLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    tipLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: 700}");

    // 3. 创建滚动区域
    QScrollArea *scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px;}");
    scrollArea->verticalScrollBar()->setStyleSheet(
        "QScrollBar:vertical { width: 2px; background-color: rgb(255, 255, 255) }");
    scrollArea->setStyleSheet("QScrollArea { border:none; }");
    layout->addWidget(scrollArea, 1);

    // 4. 创建滚动区域中的 QWidget
    _selectedContainer = new QWidget();
    _selectedContainer->setObjectName("_selectedContainer");
    _selectedContainer->setStyleSheet("#_selectedContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(_selectedContainer);

    // 5. 创建 _selectedContainer 中的 垂直布局
    QVBoxLayout *vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    _selectedContainer->setLayout(vlayout);

    // 6. 创建底部按钮
    QString style = "QPushButton { color: rgb(7, 191, 96); background-color: rgb(240, 240, 240); border: none; "
                    "border-radius: 5px;}";
    style += "QPushButton:hover { background-color: rgb(220, 220, 220); } QPushButton:pressed { background-color: "
             "rgb(200, 200, 200); }";

    QPushButton *okBtn = new QPushButton();
    okBtn->setFixedHeight(40);
    okBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    okBtn->setText("完成");
    okBtn->setStyleSheet(style);

    QPushButton *cancelBtn = new QPushButton();
    cancelBtn->setFixedHeight(40);
    cancelBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    cancelBtn->setText("取消");
    cancelBtn->setStyleSheet(style);

    // 7. 添加到布局管理器中
    gridLayout->addWidget(tipLabel, 0, 0, 1, 9);
    gridLayout->addWidget(scrollArea, 1, 0, 1, 9);
    gridLayout->addWidget(okBtn, 2, 1, 1, 3);
    gridLayout->addWidget(cancelBtn, 2, 5, 1, 3);

#if 0
    // 此处的数据通过勾选左侧列表来生成.
    QIcon defaultAvatar(":/resource/image/defaultAvatar.png");
    for (int i = 0; i < 10; ++i)
    {
        this->addSelectedFriend(QString::number(1000 + i), defaultAvatar, "张三" + QString::number(i));
    }
#endif
}
